﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Collections;
namespace XmlTestProject
{
    class xmlHandler
    {
        /// <summary>
        /// This method creates a XML file in the specified path and with the specified Root node
        /// </summary>
        /// <param name="filepath">The file path for the xml to be stored in</param>
        /// <param name="xmlRootElementId">the name of the XML root node</param>
        public void createNewXmlFile(String filepath,String xmlRootElementId)
        {
            //Create
            //XmlTextWriter class is used to create an Xml file. In this, 
            //we just specify the filepath and type of xml encoding.after that, we have to create a root element of xml document.
            //Ex: We are going to create an xml file with CustomerDetails as root element

            XmlTextWriter xtw;  //create instance for xmltextwriter. Xml Text Writer
            xtw = new XmlTextWriter(filepath, Encoding.UTF8);//assign  file path and encoding
            xtw.WriteStartDocument(); //write start document
            xtw.WriteStartElement(xmlRootElementId); //create root element
            xtw.WriteEndElement(); //end root element
            xtw.Close(); //close file. It is automatically saved.
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="ElementName"></param>
        /// <param name="Attribute"></param>
        /// <param name="AttrubuteValue"></param>
        /// <param name="Subelemnt"></param>
        /// <param name="subelemntText"></param>
        private void addDataToXmlDataBase(String filepath, String ElementName, String Attribute, String AttrubuteValue, String Subelemnt, String subelemntText)
        {
            //Write- [insert into database]
            //We can add data into an xml file by just adding child nodes to the root element. In this, we just create some
            // xml elements and append those elements to the root as a child element and save the xml document.
            //Before writing, one thing is very important. All the data stored into the xml 
            //file will be treated as String only. So we must convert all data types to string.
            // Ex: We just add a customer "abc" with address as "xyz,india"

            XmlDocument xd = new XmlDocument();     //object creation for XmlDocument class
            FileStream lfile = new FileStream(filepath, FileMode.Open); //open an xml file using file stream
            xd.Load(lfile); //load opened file in xml document
            XmlElement cl = xd.CreateElement(ElementName); //create an xml element
            cl.SetAttribute(Attribute, AttrubuteValue); //set attribute for that element
            XmlElement na = xd.CreateElement(Subelemnt); //create an xml element
            XmlText natext = xd.CreateTextNode(subelemntText); //create text for xml element
            na.AppendChild(natext); //append address text to address node
            cl.AppendChild(na); //append address node to root element
            xd.DocumentElement.AppendChild(cl); //append root element to xml document
            lfile.Close(); //close the file stream
            xd.Save(filepath); //save the xmldocument content to the file
        }
        /// <summary>
        /// This method adds a group to the database
        /// </summary>
        /// <param name="filepath">path of the database</param>
        /// <param name="groupName">The name of the group to be added</param>
        public void addGroupToDataBase(String filepath, String groupName)
        {
            String[] groups = fetchGroupsFromDataBase(filepath); 

            if (groups != null) //if the database is not empty of groups
                if (groups.Contains<String>(groupName) == true) //if group allready exsists in database
                    return; //return
             addDataToXmlDataBase(filepath, "GROUP", "ID", "SOURCE_GROUP", "NAME", groupName); //add the group to database
            
        }

        public String[] fetchDataFromDataBase(String filepath, String ElementName, String Attribute, String AttrubuteValue, String Subelemnt, String subelemntText)
        {
          //  Read-[fetch data]
          //We can retrieve data from an xml file using XmlDocument class.here we just retrieve data based on the name of the element.we fetch data as whole and take what we want by navigating through its contents.
          //This reading will return everything as String only.After reading we must convert the data into its original datatype.
          //Ex: Here we just read the address of the customer named as "abc"
           
            XmlDocument xdoc = new XmlDocument(); //creation of XmlDocument class Instance
            FileStream rfile = new FileStream(filepath, FileMode.Open); //create a file stream and open the file to be updated
            xdoc.Load(rfile);//load file into xmldocument instance
            ArrayList resualtsList = new ArrayList(); //create array List to store multipile resualts
            XmlNodeList list = xdoc.GetElementsByTagName(ElementName); //find out the no of elements available in xml file   
            for (int i = 0; i < list.Count; i++) //navigate through each and every nodes
            {
                XmlElement cl = (XmlElement)xdoc.GetElementsByTagName(ElementName)[i]; //retrieve the customer node
                XmlElement add = (XmlElement)xdoc.GetElementsByTagName(Subelemnt)[i]; //retrieve the addresss node
                if ((cl.GetAttribute(Attribute)) == AttrubuteValue) //compare it with node to be read
                {
                    resualtsList.Add(add.InnerText); //assign the arrayList as innertext of node
                }
            }
            rfile.Close(); //close the file stream
           

            String[] results = (String[])resualtsList.ToArray(typeof(string));
            if (results.Length>0)
                return results;
            return null;
        }
        
        public String[] fetchGroupsFromDataBase(String filePath)
        {
            return fetchDataFromDataBase(filePath, "GROUP", "ID", "SOURCE_GROUP", "NAME", "TEST"); 
        }


    }
}
